package com.dxl.web.common.controller;

import java.io.File;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.dxl.common.annotation.RequirePermission;
import com.dxl.common.id.UUIDGenerator;
import com.dxl.common.model.RespData;
import com.dxl.common.utils.DateUtils;
import com.dxl.common.utils.FileUtils;
import com.dxl.common.utils.Utils;
import com.dxl.service.sysprop.SysPropCacheManager;

/**
 * 文件上传控制器
 * @author 邓小林
 */
@Controller
@RequirePermission(value={"UPLOAD-MODULE"}, name="上传模块", desc="包括所有文件上传")
public class UploadController extends BaseController {
	private static final Logger LOG = Logger.getLogger(UploadController.class);
	
	@ResponseBody
	@RequestMapping(value = "/upload", method=RequestMethod.POST)
	@RequirePermission(value={"FILE-UPLOAD"}, name="文件上传", desc="通用文件上传")
	public RespData upload(HttpServletRequest req) {
		if (!ServletFileUpload.isMultipartContent(req)) {
			return RespData.instance(RespData.FAIL, "请选择要上传的文件");
		}
		Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest) req).getFileMap();
		if (Utils.isNull(fileMap) || fileMap.isEmpty()) {
			return RespData.instance(RespData.FAIL, "请选择要上传文件");
		}
		Iterator<MultipartFile> it = fileMap.values().iterator();
		MultipartFile mFile;
		String errorMsg = "", uri, path;
		File file;
		Set<String> uris = new LinkedHashSet<String>();
		while (it.hasNext()) {
			mFile = it.next();
			try {
				uri = getUri(mFile);
				path = SysPropCacheManager.getRootDir() + uri.replace("/", File.separator);
				file = new File(path);
				FileUtils.ensureFile(path);
				mFile.transferTo(file);
				uris.add(uri);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
				if (Utils.isBlank(errorMsg)) {
					errorMsg += ",";
				}
				errorMsg += mFile.getOriginalFilename();
			}
		}
		if (Utils.isNotBlank(errorMsg)) {
			return RespData.instance(RespData.SUCCESS, errorMsg + "上传失败");
		}
		return RespData.instance(RespData.SUCCESS, "上传成功", uris.size() > 1 ? uris.iterator().next() : uris);
	}
	
	private static String getUri(MultipartFile mFile) {
		String path = "/uploaded/" + DateUtils.formatDate(new Date(), DateUtils.DF_yyyyMMdd) + "/" + UUIDGenerator.get().genUUID() + "." + FileUtils.fileSuffix(mFile.getOriginalFilename());
		return path;
	}
}
